<?php

namespace app\common\cachemodel;

use app\common\cachemodel\zl2\Zl2FamousPersonRecode;
use app\common\lib\astrolog\SynastryData;
use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * 合盘结果记录
 */
class AppSynastryResult extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_synastry_result';

    protected $cacheModel = 'user.synastry';
    protected $cacheModel1 = 'synastry.ranking';
    protected $cacheModel2 = 'synastry.famous_person_ranking';
    /**
     * 缓存id键名 为空时不更新
     * @var string
     */
    protected $cacheIdKey = 'id';

    /**
     * 获取合盘分数排行榜列表
     * 只显示20条数据
     * score
     * nickname1 自己档案的昵称
     * nickname2
     * avatar1
     * avatar2
     * relation
     * create_time
     * @throws \Exception
     */
    public function getList()
    {
        // 获取排行榜前100名用户的合盘数据ID集
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel1)
            ->setPage(1)
            ->setPageSize(100)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc')
            {
                $resData = $this->getRankingIdsInData();
                if ($isCache)
                {
                    $data = [];
                    foreach ($resData as $uid => $score)
                    {
                        $data[$uid] = ['score' => $score];
                    }
                    return $data;
                }
                return $resData;
            }, 'score', 0);

        $ids = [];// 排行榜前100的ID
        foreach ($pageData['data'] as $uid => $score)
        {
            $score = sprintf("%01.8f", $score);
            $s = explode('.', $score)[1];
            $ids[] = 100000000 - $s;
        }

        $dataList = $this->batchGetInfoByIds($ids, ['score', 'uid', 'nickname1', 'nickname2', 'avatar1', 'avatar2', 'relation', 'create_time']);

        $pageData['data'] = array_values($dataList);

        return $pageData;
    }

    /**
     * 获取用户排行榜排名
     */
    public function userRankingIndex($uid): int
    {
        // 获取排行榜前100名用户的合盘数据ID集
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel1)
            ->setPage(1)
            ->setPageSize(100)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc')
            {
                $resData = $this->getRankingIdsInData();
                if ($isCache)
                {
                    $data = [];
                    foreach ($resData as $uid => $score)
                    {
                        $data[$uid] = ['score' => $score];
                    }
                    return $data;
                }
                return $resData;
            }, 'score', 0);

        $uids = array_flip(array_keys($pageData['data']));

        return isset($uids[$uid]) ? $uids[$uid] + 1 : 0;
    }

    /**
     * 开启了缓存
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where('uid', $type[0]);
            }

            $synastryResult = $this->where('status', 1)
                ->order('id ' . $sortType)
                ->column('uid,create_time,synastry_type,create_type,update_time,nickname1,nickname2,avatar1,avatar2,score,relation,extra,type,rid1,rid2', 'id');

            foreach ($synastryResult as $id => $item)
            {
                $synastryResult[$id]['order_score'] = $item['update_time'] + ($id / 100000000);
            }
        }
        catch (\Exception $e)
        {
            Log::write('合盘结果获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $synastryResult;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'create_type', 'rid1', 'rid2', 'synastry_type', 'score', 'type', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 获取排行榜前100名用户和分数
     * @return array
     */
    public function getRankingIdsInData()
    {
        try
        {
            return [];
            // 同时有两个相同最大分数时会取多条 bug
            $data = $this->alias('a')->where('score', 'eq', function ($query)
            {
                $query->table('wechat_backup_07_18_14_43_00.app_synastry_result')->where('a.uid=uid')->field('Max(score)');
            })->group('uid')->order('score desc,id asc')->limit(100)->column('id,score', 'uid');

            $resData = [];
            foreach ($data as $uid => $datum)
            {
                $resData[$uid] = $datum['score'] + ((100000000 - $datum['id']) / 100000000);
            }
        }
        catch (\Exception $e)
        {
            return [];
        }

        return $resData;
    }

    /**
     * 保存合盘记录
     * 若分数超过排行榜最低分，需要更新榜单
     * uid 合盘的用户id
     * type tinyint 1=>普通合盘 2=>明星合盘
     * rid1 ing rid1
     * rid2 int rid2
     * create_time bigint 创建时间
     * update_time bigint 更新时间
     * nickname1 varchar(50) 档案1昵称
     * nickname2 varchar(50) 档案2昵称
     * avatar1 string 档案1头像
     * avatar2 string 档案2头像
     * score int 合盘分数
     * relation string 最适合的关系
     * extra json 保存合盘的两个档案信息
     * @param array $data
     * @param bool $isUpdateRanking 是否检查并更新排行榜
     * @return bool|int
     */
    public function saveData(array $data = [], $isUpdateRanking = false)
    {
        try
        {
            $data['synastry_type'] = $data['synastry_type'] ?? 0;
            $id = null;
            if (isset($data['rid1'], $data['rid2']) && $data['rid1'] && $data['rid2'])
            {
                $id = $this->where(['uid' => $data['uid'], 'status' => 1, 'type' => $data['type'], 'rid1' => $data['rid1'], 'rid2' => $data['rid2'], 'synastry_type' => $data['synastry_type']])->value('id');
            }

            if ($id)
            {
                unset($data['create_time']);
                $this->allowField(true)->isUpdate(true)->save($data, ['id' => $id]);
            } else
            {
                $id = $this->allowField(true)->insertGetId($data);

                if (isset($data['type']) && $data['type'] === 5)
                {
                    $famousPersonRecodeModel = new Zl2FamousPersonRecode();
                    $synastryNum = $famousPersonRecodeModel->getInfoById($data['rid2'], ['synastry_num']);
                    $famousPersonRecodeModel->updateData($data['rid2'], ['synastry_num' => $synastryNum['synastry_num'] + 1]);
                }
            }

            if ($isUpdateRanking)
            {
                // 获取排行榜上排名
                $this->rankingCacheAddChange($data['uid'], $id, $data['score']);
            }

            $score = ($data['update_time'] ?? 0) + ($id / 100000000);
            // 写入缓存 列表缓存
            $this->listDataAdd($data['uid'], [$id => $score]);
            if (isset($data['type'], $data['rid2'], $data['score'], $data['uid']) && $data['type'] === 5)
            {   // 名人排行榜 添加数据
                CacheManage::getInstance()->setCacheConfig($this->cacheModel2, $data['rid2'])->listAdd([$id => $data['score']]);
                // 用户 名人合盘列表
                CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('famous_person_list', $data['uid'])->listAdd([$id => $id], 0, 'famous_person_list');
            }
        }
        catch (\Exception $e)
        {
            Log::write('合盘记录数据写入错误：' . $e->getMessage(), 'error', true);
            return false;
        }

        return $id;
    }

    /**
     * 排行榜缓存数据添加
     * @param $uid
     * @param $id
     * @param $score
     * @throws \Exception
     */
    private function rankingCacheAddChange($uid, $id, $score)
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $cacheScore = $redis->zScore('synastry:ranking:list', $uid);

        if (!$cacheScore || $score > $cacheScore)
        {   // 如果缓存中用户分数不存在 或者分数大于缓存中的分数
            CacheManage::getInstance()->setCacheConfig($this->cacheModel1)->listAdd([$uid => $score + ((100000000 - $id) / 100000000)]);
        }
    }

    /**
     * 删除/隐藏合盘记录
     * 更新 status=0,update_time=删除时间
     * @param int $uid 用户id
     * @param int $id 合盘记录id
     * @return bool
     */
    public function delData($uid, $id)
    {
        try
        {
            $this->where(['id' => $id])->update(['status' => 0, 'update_time' => time()]);
            // 删除缓存 列表缓存
            $this->listDataDel($uid, [$id]);
        }
        catch (\Exception $e)
        {
            Log::write('合盘记录数据删除错误：' . $e->getMessage(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取用户合盘记录
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserList($uid = 0, $page = 1, $limit = 10)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType(0)// 类型 用于分页 例如 0全部
            ->getListPage(function ($ids, $isCache = true, $sortType = 'asc') use ($uid, $page, $limit)
            {
                // 开启了缓存
                if ($isCache)
                {
                    return $this->getInfoByIdsInData($ids, [$uid, 0], $sortType);
                }

                // 没开启缓存
                return $this->getUserPaginateInData($uid, $sortType, $page, $limit);
            }, 'order_score', ['id', 'score', 'nickname1', 'nickname2', 'avatar1', 'avatar2', 'relation', 'create_time', 'type'], 0);

        $data = [];
        foreach ($pageData['data'] as $datum)
        {
            $data[] = [
                'id' => (int)$datum['id'],
                'score' => (int)$datum['score'],
                'nickname1' => $datum['nickname1'],
                'nickname2' => $datum['nickname2'],
                'avatar1' => $datum['avatar1'],
                'avatar2' => $datum['avatar2'],
                'relation' => $datum['relation'],
                'create_time' => (int)$datum['create_time'],
                'type' => in_array((int)$datum['type'], [5, 6], true) ? (int)$datum['type'] : 1,
            ];
        }
        $pageData['data'] = $data;

        return $pageData;
    }

    /**
     * 获取用户合盘记录
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserList2($uid = 0, $page = 1, $limit = 10)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType(0)// 类型 用于分页 例如 0全部
            ->getListPage(function ($ids, $isCache = true, $sortType = 'asc') use ($uid, $page, $limit)
            {
                // 开启了缓存
                if ($isCache)
                {
                    return $this->getInfoByIdsInData($ids, [$uid, 0], $sortType);
                }

                // 没开启缓存
                return $this->getUserPaginateInData($uid, $sortType, $page, $limit);
            }, 'order_score', [], 0);

        $data = [];
        foreach ($pageData['data'] as $datum)
        {
            $datum = arrayKeyData2int($datum, ['id', 'uid', 'create_time', 'create_type', 'update_time', 'score', 'type', 'rid1', 'rid2', 'synastry_type']);
            // type = 合盘类型 1=>普通合盘 2=>明星合盘 3=>有档案被删除  4=>活动邀请合盘未创建档案 5=>名人合盘 6=>邀请好友填档案合盘（不添加档案） 7=>大众合盘 8=>恋爱合盘  9=>婚姻合盘 10=>事业合盘  11=>朋友合盘  12=>星座合盘
            $synastryType = in_array($datum['synastry_type'], [7, 8, 9, 10, 11, 12], true) ? $datum['synastry_type'] : 1;

            if ($datum['type'] === 5 || $datum['synastry_type'] == 5)
            {
                if (Util::ZyhsIsHuaweiOrHonorHg(2))
                {
                    $tip = '名人';
                } else
                {
                    $tip = '名人合盘';
                }
            } else
            {
                switch ($synastryType)
                {
                    case 8:
                        $tip = '恋爱';
                        $datum['relation'] = '恋人';
                        break;
                    case 9:
                        $tip = '婚姻';
                        $datum['relation'] = '婚姻';
                        break;
                    case 10:
                        $tip = '事业';
                        $datum['relation'] = '同事';
                        break;
                    case 11:
                        $tip = '朋友';
                        $datum['relation'] = '朋友';
                        break;
                    case 12:
                        $tip = '星座';
                        break;
                    default:
                        $tip = '大众';
                }
                if ($datum['create_type'] === 1)
                {   // 邀请
                    $tip = '邀请-' . $tip;
                } else
                {
                    if (Util::ZyhsIsHuaweiOrHonorHg(2))
                    {
                        $tip .= '关系';
                    } else
                    {
                        $tip .= '合盘';
                    }

                }
            }

            $data[] = [
                'id' => (int)$datum['id'],
                'score' => (int)$datum['score'],
                'nickname1' => $datum['nickname1'],
                'nickname2' => $datum['nickname2'],
                'avatar1' => $datum['avatar1'],
                'avatar2' => $datum['avatar2'],
                'relation' => $datum['relation'],
                'create_time' => (int)$datum['create_time'],
                'synastry_type' => $synastryType,   //
                'tip' => $tip,
            ];
        }
        $pageData['data'] = $data;

        return $pageData;
    }

    /**
     * 没开启缓存
     * @param $uid
     * @param string $sortType
     * @param $page
     * @param $limit
     * @return array|false|string
     */
    public function getUserPaginateInData($uid, $sortType, $page, $limit)
    {
        try
        {
            $synastryResult = $this
                ->where('uid', $uid)
                ->where('status', 1)
                ->order("update_time {$sortType},id {$sortType}")
                ->field('id,create_time,create_type,nickname1,nickname2,avatar1,avatar2,score,relation,extra')
                ->paginate($limit, false, ['page' => $page]);
        }
        catch (\Exception $e)
        {
            Log::write('合盘结果获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $synastryResult;
    }

    /**
     * 获取用户最高分合盘记录
     * TODO 添加缓存
     * @param $uid
     * @return array
     */
    public function getUserHighestScore($uid)
    {
        if ($uid)
        {
            try
            {
                $res = $this
                    ->field('id,nickname1,nickname2,avatar1,avatar2,score,relation')
                    ->where('uid', $uid)
                    ->order('score desc,create_time asc')
                    ->limit(3)
                    ->selectOrFail();
            }
            catch (\Exception $e)
            {
//                Log::error('获取用户最高合盘分数异常：' . $e->getMessage());
                $res = [];
            }
        } else
        {
            $res = [];
        }

        return $res;
    }

    /**
     * 档案删除 -- 将该档案合盘记录类型改为3【合盘类型 1=>普通合盘 2=>明星合盘 3=>有档案被删除  4=>活动邀请合盘未创建档案】
     * @param int $rid
     * @param int $uid
     */
    public function recodeDel(int $rid, int $uid): void
    {
        try
        {
            // 获取当前档案的合盘数据IDS
            $ids = $this->where(['uid' => $uid, 'status' => 1, 'rid1|rid2' => $rid])->column('id');
            // 更新数据库内数据状态
            $this->whereIn('id', $ids)->update(['type' => 3]);
            foreach ($ids as $id)
            {   // 更新缓存
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache(['type' => 3]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('档案删除，更新档案合盘记录类型错误：' . $e->getMessage(), 'error', true);
        }
    }

    /**
     * 获取名人排行榜
     * @param int $fpId 名人ID
     * @return array
     * @throws \Exception
     */
    public function getFamousPersonRanking(int $fpId)
    {
        // 获取排行榜前100名用户的合盘数据ID集
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel2, $fpId)
            ->setPage(1)
            ->setPageSize(100)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($fpId)
            {
                return $this->getFamousPersonRankingIdsInData($fpId);
            }, 'score', 0);

        $resData = [];
        foreach ($pageData['data'] as $id => $score)
        {
            $resData[$id] = [
                'id' => $id,
                'score' => (int)$score,
            ];
        }
        return $resData;
    }

    /**
     * 初始化 名人星盘排行榜缓存数据
     * @param int $fpId
     * @return array
     */
    public function getFamousPersonRankingIdsInData(int $fpId)
    {
        try
        {
            // 同时有两个相同最大分数时会取多条 bug
            $data = $this->where(['type' => 5, 'rid2' => $fpId])
                ->order('score desc,id asc')->limit(100)->column('score', 'id');

            $resData = [];
            foreach ($data as $id => $score)
            {
                $resData[$id] = ['score' => $score + ((100000000 - $id) / 100000000)];
            }
        }
        catch (\Exception $e)
        {
            return [];
        }

        return $resData;
    }

    /**
     * 获取名人排行信息
     * @param int $fpid
     * @return void
     * @throws \Exception
     */
    public function getFamousPersonRankingData(int $uid, int $fpid, int $rid)
    {
        $utilModel = new Util();
        // 获取排行榜信息
        $data = $this->getFamousPersonRanking($fpid);

        $ids = array_column(array_slice($data, 0, 20), 'id');

        $synastryData = $this->batchGetInfoByIds($ids, ['id', 'rid2', 'extra', 'score']);
        // 获取用户名人合盘信息
        $synastryInfo = $this->getUserFamousPersonList($uid, $fpid);
        $btnInfo = [
            'title' => '与TA合盘冲击排行榜',
            'target' => 'local',
            'link' => "synastry_result?type=5&rid1={$rid}&rid2={$fpid}&need_auth=1",
            'icon' => '/test/synastry/synastry_ranking.png',
            'type' => 1,
        ];
        if ($synastryInfo)
        {
            $recodeInfo = (new Recode())->getInfoById($rid, ['type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'ew', 'long_deg', 'long_min', 'ns', 'lat_deg', 'lat_min', 'is_summer', 'sun', 'moon', 'asc']);
            $recodeHash = Util::getRecodeHashKey($recodeInfo);
            if ($synastryInfo['hash'] !== $recodeHash)
            {
                $synastryInfo = null; // 档案信息更新 不记录合盘信息
            } else
            {
                $btnInfo = [
                    'title' => "已完成合盘/{$synastryInfo['score']}分",
                    'target' => 'local',
                    'link' => "synastry_result?type=1&id={$synastryInfo['id']}&need_auth=1",
                    'icon' => '/test/synastry/synastry_go.png',
                    'type' => 2,
                ];
            }
        }
        // 获取排行榜信息
        $rankingList = [];
        $ranking = 1;
        foreach ($ids as $idItem)
        {
            if (!isset($synastryData[$idItem]))
            {   // 档案删除 跳过
                // 排行榜内缓存删除
                CacheManage::getInstance()->setCacheConfig($this->cacheModel2, $fpid)->delJudge([$idItem]);
                continue;
            }
            $synastryDataItem = $synastryData[$idItem];
            $recodeData = json_decode($synastryDataItem['extra'], true);
            $userDes = '日' . $utilModel->recodeAstroShorthand($recodeData['recode1']['sun']) . '月' . $utilModel->recodeAstroShorthand($recodeData['recode1']['moon']) . '升' . $utilModel->recodeAstroShorthand($recodeData['recode1']['asc']);
            $rankingList[] = [
                'name' => $recodeData['recode1']['name_old'] ?? '',
                'avatar' => $recodeData['recode1']['avatar'] ?? '',
                'des' => $userDes,
                'score' => (int)$synastryDataItem['score'],
                'ranking' => $ranking,
            ];
            $ranking++;
        }

        $mySynastryInfo = null;
        $shareData = null;
        $shareTitle = '';
        if ($synastryInfo)
        {
            $selfDes = '日' . $utilModel->recodeAstroShorthand($synastryInfo['extra']['recode1']['sun']) . '月' . $utilModel->recodeAstroShorthand($synastryInfo['extra']['recode1']['moon']) . '升' . $utilModel->recodeAstroShorthand($synastryInfo['extra']['recode1']['asc']);
            if (isset($data[$synastryInfo['id']]))
            {   // 100名以内
                // 获取排名
                $ranking = 1;
                foreach ($data as $dataItem)
                {
                    if ($dataItem['id'] === $synastryInfo['id'])
                    {
                        break;
                    }
                    $ranking++;
                }
                if ($ranking <= 20)
                {
                    $shareTitle = "恭喜你在全国排名第{$ranking}名";
                }
                $rankingDes = (string)$ranking;
            } else
            {   // 100+
                $rankingDes = '100+';
            }

            if (empty($shareTitle))
            {
                // 获取 名人信息
                $famousPersonInfo = (new Zl2FamousPersonRecode())->getInfoById($fpid, ['synastry_num']);

                if ($famousPersonInfo['synastry_num'] > 0)
                {
                    $percent = sprintf('%.2f', ($famousPersonInfo['synastry_num'] - $ranking) / $famousPersonInfo['synastry_num']) * 100;
                    if ($percent < 0)
                    {
                        $percent = 1;
                    }
                } else
                {
                    $percent = 1;
                }

                $shareTitle = "击败了全国{$percent}%的小行星";
            }
            $synastryInfo['extra']['type'] = 1;
            $synastryScore = (new SynastryData())->getScore($synastryInfo['extra']);
            $mySynastryInfo = [
                'name' => $synastryInfo['extra']['recode1']['name_old'] ?? '',
                'avatar' => $synastryInfo['extra']['recode1']['avatar'] ?? '',
                'des' => $selfDes,
                'score' => $synastryInfo['score'],
                'ranking_des' => $rankingDes,
            ];
            $shareData = [
                'harmoniousAndConflict' => $synastryScore['harmoniousAndConflict'],
                'name1' => $synastryInfo['extra']['recode1']['name_old'] ?? '',
                'avatar1' => $synastryInfo['extra']['recode1']['avatar'] ?? '',
                'name2' => $synastryInfo['extra']['recode2']['name'] ?? '',
                'avatar2' => $synastryInfo['extra']['recode2']['avatar'] ?? '',
                'title' => $shareTitle,
                'score' => $synastryInfo['score'],
            ];
        }

        $resData = [
            'my_synastry_info' => $mySynastryInfo,
            'share_data' => $shareData,
            'ranking_list' => $rankingList,
            'btn_info' => $btnInfo,
        ];

        return $resData;
    }

    /**
     * 获取用户名人合盘信息
     * @return array
     */
    public function getUserFamousPersonList(int $uid, int $fpid = 0)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('famous_person_list', $uid)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $reIds = $this->where(['uid' => $uid, 'type' => 5, 'status' => 1])->column('id');

                    $d = [];
                    foreach ($reIds as $id)
                    {
                        $d[$id] = ['id' => $id];
                    }

                    return $d;
                }
                catch (\Exception $e)
                {
                    Log::write('AppSynastryResult model => getUserFamousPersonList() 获取名人合盘历史ID异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                    return [];
                }
            }, 'id', 0, 'famous_person_list');

        $datas = $this->batchGetInfoByIds(array_keys($pageData['data']), ['id', 'rid2', 'extra', 'score']);

        $resData = [];
        foreach ($datas as $id => $dataItem)
        {
            if ($fpid)
            {
                if ($fpid == $dataItem['rid2'])
                {
                    $dataItem['id'] = (int)$dataItem['id'];
                    $dataItem['rid2'] = (int)$dataItem['rid2'];
                    $dataItem['score'] = (int)$dataItem['score'];
                    $dataItem['extra'] = json_decode($dataItem['extra'], true);
                    $dataItem['hash'] = Util::getRecodeHashKey($dataItem['extra']['recode1']);
                    return $dataItem;
                } else
                {
                    continue;
                }
            }
            $recodes = json_decode($dataItem['extra'], true);

            $resData[$dataItem['rid2']] = [
                'id' => (int)$id,
                'hash' => Util::getRecodeHashKey($recodes['recode1']),
                'score' => (int)$dataItem['score'],
            ];
        }

        return $resData;
    }
}
